#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtWidgets>
#include <chrono>

namespace{
const char* g_host{"10.0.3.188"};
constexpr uint16_t g_port{8080};
}

#define RETURN_ENTER "\r\n"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("QtHPClient");
    OnInitDialog();
}

MainWindow::~MainWindow()
{
    delete ui;
    m_exit = true;
    m_cv.notify_all();
    m_state = ThreadState::IDLE_STATE;
    if(m_work_thread.joinable())m_work_thread.join();
    if(m_client)
    {
        m_client->Stop();
        HP_Destroy_TcpClient(m_client);
    }
}

void MainWindow::OnInitDialog()
{
    InitClient();
    InitWorkThread();
    if(m_client)
    {
        m_client->Start(g_host,g_port,TRUE);
        QTimer::singleShot(1000,this,[this]{m_state = ThreadState::CALCULATE_STATE;});
    }
}

void MainWindow::InitClient()
{
    if(nullptr == m_client)
        m_client = HP_Create_TcpClient(&m_client_listener);
    Q_ASSERT(m_client);
    connect(&m_client_listener,&testsignalhp::signal_connect_notify,this,[](CONNID dwConnID,const QString&client_info,bool conn){
        qDebug()<<"ConnID: "<<dwConnID<<"Client Info: "<<client_info<<((conn)?" Ok":" Fail")<<RETURN_ENTER;
    });

    connect(&m_client_listener,&testsignalhp::signal_msg_notify,this,[](CONNID dwConnID,const uint8_t*pData,int iLength){
        qDebug()<<"ConnID: "<<dwConnID<<"Data: "<<QString::fromLatin1((const char*)pData,iLength)<<RETURN_ENTER;
    });
}

void MainWindow::InitWorkThread()
{
    m_work_thread = std::thread([this]{
        std::unique_lock<std::mutex>loc(m_mutex);
        int count{0};
        while (!m_exit) {
            switch (m_state) {
            case ThreadState::IDLE_STATE:
            {
                m_cv.wait_for(loc,std::chrono::milliseconds(200),[this]{return m_exit;});
                continue;
            }
                break;
            case ThreadState::CALCULATE_STATE:
            {
                QString str{QString("Count is %1").arg(count++)};
                if(m_client)
                    m_client->Send((uint8_t*)str.toLatin1().data(),str.length());
                m_cv.wait_for(loc,std::chrono::milliseconds(50),[this]{return m_exit;});
            }
                break;
            }
        }//while(!exit)
    });
}

